package com.lagou.rpc.client;

import com.lagou.encoder.RpcEncoder;
import com.lagou.request.RpcRequest;
import com.lagou.rpc.handler.UserClientHandler;
import com.lagou.serializer.JSONSerializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Client
 *
 * @author zyt
 * @date 2020/8/12 20:49
 */
public class Client {

    // 创建线程池
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    // 声明自定义事件处理器
    private static UserClientHandler userClientHandler;

    // 初始化客户端（创建连接池、bootstrap，设置bootstrap、连接服务器）
    private static void initClient() throws InterruptedException {
        // 线程池
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        userClientHandler = new UserClientHandler();

        // 启动引导对象
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()))
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()))
                                .addLast(new StringDecoder())
                                .addLast(userClientHandler);
                    }
                });

        bootstrap.connect("127.0.0.1", 8080).sync();

    }

    // jdk动态代理，创建对象
    public static Object createProxy(final Class<?> serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                // 初始化客户端
                if (userClientHandler == null) {
                    initClient();
                }

                // 封装RpcRequest
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setClassName(serviceClass.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameterTypes(method.getParameterTypes());
                rpcRequest.setParameters(args);

                // 设置参数
                userClientHandler.setParams(rpcRequest);

                // 使用线程池，开启一个线程远程调用
                Object result = executorService.submit(userClientHandler).get();

                // 返回结果
                return result;
            }
        });
    }


}
